package com.edu.web.controller.info;

import com.edu.common.annotation.Log;
import com.edu.common.core.controller.BaseController;
import com.edu.common.core.domain.AjaxResult;
import com.edu.common.core.page.TableDataInfo;
import com.edu.common.enums.BusinessType;
import com.edu.common.utils.poi.ExcelUtil;
import com.edu.framework.websocket.service.ForceNoticeService;
import com.edu.framework.websocket.service.NoticeService;
import com.edu.system.domain.TNotice;
import com.edu.system.domain.req.PublishDTO;
import com.edu.system.service.ITNoticeService;
import com.edu.system.service.ITPublishClassService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 通知Controller
 * 
 * @author xxxx
 * @date 2023-12-27
 */
@Slf4j
@RestController
@RequestMapping("/system/notice")
public class TNoticeController extends BaseController
{
    @Autowired
    private ITNoticeService tNoticeService;
    // 1通知 2校园风采
    public static Integer publishClass_type=1;
    @Resource
    private ITPublishClassService publishClassService;
    @Resource
    private NoticeService wsNoticeService;
    @Resource
    private ForceNoticeService wsForceNoticeService;


    // 1普通通知 2 强通知
    private static final Integer NOTICE_TYPE_NORMAL = 1;
    private static final Integer NOTICE_TYPE_FORCE = 2;

    /**
     * 查询通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(TNotice tNotice)
    {
        startPage();
        List<TNotice> list = tNoticeService.selectTNoticeList(tNotice);
        return getDataTable(list);
    }

    /**
     * 导出通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:export')")
    @Log(title = "通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TNotice tNotice)
    {
        tNotice.setType(NOTICE_TYPE_NORMAL);
        List<TNotice> list = tNoticeService.selectTNoticeList(tNotice);
        ExcelUtil<TNotice> util = new ExcelUtil<TNotice>(TNotice.class);
        util.exportExcel(response, list, "通知数据");
    }

    /**
     * 获取通知详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tNoticeService.selectTNoticeById(id));
    }

    /**
     * 批量发布
     */
    @PreAuthorize("@ss.hasPermi('system:notice:publish')")
    @PostMapping(value = "/publish")
    public AjaxResult publish(@RequestBody PublishDTO req)
    {
        req.setPublishType(1);
        publishClassService.savePublishClass(req);

        doPushMsg(req.getIds());
        return success();
    }

    private void doPushMsg(List<Long> ids) {
        List<Long> roomIds = publishClassService.queryClassIdsByTids(ids, 1);
        CompletableFuture.runAsync(() -> {
            wsNoticeService.pushMsg(roomIds);
            wsForceNoticeService.pushMsg(roomIds);
        });
    }

    /**
     * 上下架
     */
    @PreAuthorize("@ss.hasPermi('system:notice:onOff')")
    @GetMapping(value = "/onOff/{id}/{status}")
    public AjaxResult onOff(@PathVariable("id") Long id, @PathVariable("status") Integer status)
    {
        int i = tNoticeService.updateTNotice(TNotice.builder().id(id).status(status).build());
        return success(i);
    }

    /**
     * 新增通知
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TNotice tNotice)
    {
        tNotice.setCreateBy(getUsername());
        return toAjax(tNoticeService.insertTNotice(tNotice));
    }


    /**
     * 修改通知
     */
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TNotice tNotice)
    {
        tNotice.setUpdateBy(getUsername());
        int i = tNoticeService.updateTNotice(tNotice);

        doPushMsg(Collections.singletonList(tNotice.getId()));
        return toAjax(i);
    }

    /**
     * 删除通知
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int i = tNoticeService.deleteTNoticeByIds(ids);

        doPushMsg(Arrays.asList(ids));
        return toAjax(i);
    }


    /**
     * 下发通知
     * 异步
     * @param
     */
    private void pushMsg(List<Long> ids, Integer noticeType, boolean isCheckDouble) {
        List<Long> before = publishClassService.queryClassIdsByTids(ids, publishClass_type);
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.error("睡眠异常");
            }
            if (isCheckDouble){
                List<Long> after = publishClassService.queryClassIdsByTids(ids, publishClass_type);
                before.addAll(after);
            }
            if (noticeType.equals(NOTICE_TYPE_NORMAL)){
                wsNoticeService.buildTrigger(before);
            } else {
                wsForceNoticeService.buildTrigger(before);
            }
        });
    }
}
